import { useEffect, useState } from 'react';
import CommonTab from '@/components/CommonTab'
import FormSearch from './FormSearch';
import Summary from './Summary';
import RecordList from './RecordList';
import RecordDetail from './RecordDetail';
import { useResize } from '@/views/hooks/useResize';
import { getFieldConfig, updateFieldConfig } from '@/services/common';
import { initColumns, pageCode } from './config';


//tab源数据
const tabArr = [
	{ key: '1', tab: '快销备货汇总' },
	{ key: '2', tab: '历史打印记录' },
]

const StockSummary = () => {

	const [type, setType] = useState('1');

	//表单数据
	const [formData, setFormData] = useState({});

	//详情数据
	const [detailData, setDetailData] = useState([]);

	//是否展示详情页
	const [showDetail, setShowDetail] = useState(false);

	const [loading, setLoading] = useState(true);

	const [pageConfig, setPageConfig] = useState({
		columns: initColumns,//订单列数据
	})

	useEffect(() => {
		getPageConfig();
	}, [])

	//获取页面的配置信息
	const getPageConfig = async () => {
		START_LOADING();
		const params = {
			code: pageCode,
		}
		const { success, data = {} } = await getFieldConfig(params);
		if (success) {
			const { param = '' } = data;
			if (param) {
				setPageConfig(JSON.parse(param));
			}
		}
		END_LOADING();
		setLoading(false)
	}

	//更新配置文件
	const updatePageConfig = async (keys, val, cb) => {
		const obj = {
			...pageConfig,
			[keys]: val
		}
		const { success } = await updateFieldConfig({
			code: pageCode,
			param: JSON.stringify(obj)
		});
		if (success) {
			setPageConfig(obj);
		}
		cb && cb(success);
	}


	//监听变更
	const { el: headerEl, height: headerHeight, onResize } = useResize();

	//Tab区
	const TabProps = {
		type,
		data: tabArr,
		onChange(type) {
			setType(type)
		}
	}

	//搜索区域
	const FormSearchProps = {
		refs: headerEl,
		type,
		formData,
		handleOk(val) {
			setFormData(val);
		}
	}

	//汇总表格
	const SummaryProps = {
		formData,
		initColumns,
		headerHeight: headerHeight + 280,
		realColumns: pageConfig.columns,
		updatePageConfig,
	}

	//历史记录
	const RecordListProps = {
		formData,
		realColumns: pageConfig.columns,
		headerHeight: headerHeight + 256,
		changeShowDetail(val) {
			setDetailData(val);
			setShowDetail(true);
		}
	}

	//历史记录详情数据
	const RecordDetailProps = {
		data: detailData,
		realColumns: pageConfig.columns,
		updatePageConfig,
		changeShowDetail() {
			setShowDetail(false);
		}
	}

	if (loading) {
		return null;
	}

	return (
		<>
			<CommonTab {...TabProps} />
			{(type == '1' || !showDetail) && <FormSearch {...FormSearchProps} />}
			{type == '1' && <Summary {...SummaryProps} />}
			{type == '2' && !showDetail && <RecordList {...RecordListProps} />}
			{type == '2' && showDetail && <RecordDetail {...RecordDetailProps} />}
		</>

	);
};
export default StockSummary;